# -*- coding: utf-8 -*-
import sys
import arcpy
import numpy as np
import pandas as pd

def table_to_csv(input_fc="RasterUnitsV4_2003", year=2003, sel_fields="", saved_filename = "",
                 additional_process_fun=None):
    '''
        将要素类的属性表转为csv文件
    :param input_fc: Feature Class
        输入的要素类

    :param year: int
        年份

    :param sel_fields: str
        需要导出的字段列表，字符串形式，以分号;分隔，形式如：Factor_Aspect;Factor_地震点_IDW3

    :param additional_process_fun: function
        函数引用，将sel_fields使用传入的函数进行处理，默认值为None

    :return: str
        返回保存的csv文件名

    '''
    if input_fc is None or year is None:
        return None

    # 若未选择需要导出的字段，则导出所有字段（shape字段除外）
    if sel_fields == "":
        # 删除Shape字段
        field_obj_list = arcpy.ListFields(input_fc)
        field_list = [f.name for f in field_obj_list]
        field_list.remove("Shape")

    elif len(sel_fields)!=0:
        field_list = sel_fields.split(";")
        if "OBJECTID" not in field_list:
            field_list.insert(0,"OBJECTID")

    if "Shape_Length" in field_list:
        field_list.remove("Shape_Length")
    if "Shape_Area" in field_list:
        field_list.remove("Shape_Area")
    # 使用传入的函数进行额外处理
    if additional_process_fun is not None:
        field_list = additional_process_fun(field_list)

    header_titles = ",".join(field_list)

    try:
    # 输出属性表至csv文件
        arr = arcpy.da.FeatureClassToNumPyArray(input_fc, field_list, skip_nulls=True)
    except Exception:
        print("error:")
        e = sys.exc_info()[1]
        print(e.args[0])

    # 若没有指定保存文件的路径，则自动设置一个路径
    if saved_filename == "":
        saved_filename = "{0}_{1}.csv".format(input_fc, year)
    df = pd.DataFrame(data=arr, columns=field_list)
    df.to_csv(saved_filename, header=header_titles, encoding="gb2312", index=False)

    # #encoding参数numpy 1.14.0开始支持
    # np.savetxt(saved_filename, arr,
    #               header=header_titles,
    #               fmt=fmt_str,
    #               delimiter=",",
    #               encoding="utf-8")
    success_str = "write file '{0}' to csv successful!".format(saved_filename)
    arcpy.AddMessage(success_str)
    return saved_filename

if __name__ == "__main__":
    input_fc = arcpy.GetParameterAsText(0)
    year = int(arcpy.GetParameterAsText(1))
    export_fields = arcpy.GetParameterAsText(2)
    csv_file_path = arcpy.GetParameterAsText(3)
    export_fields = export_fields.strip()
    csv_file_path = csv_file_path.strip()

    table_to_csv(input_fc=input_fc, year=year, sel_fields=export_fields, saved_filename=csv_file_path)

    # # 代码模式下，需要设定工作区间
    # arcpy.env.workspace = "G:/DataForDoctorPaper/博士论文数据.gdb"
    # export_fields = "Factor_Aspect;Factor_地震点_IDW3;Factor_断层距离;Factor_流路长度"
    # table_to_csv(input_fc='RasterUnitsV4_2003', year=2003, sel_fields=export_fields, saved_filename=csv_file_path)